package com.cssl.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import com.cssl.domain.dto.DtsCartDto;
import com.cssl.mapper.DtsCartMapper;
import com.cssl.mapper.DtsGoodsMapper;
import com.cssl.service.DtsCartService;
import com.cssl.util.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Service
public class DtsCartServiceImpl implements DtsCartService {
    @Resource
    private DtsCartMapper cartMapper;
    @Resource
    private DtsGoodsMapper goodsMapper;
    @Autowired
    private ThreadPool threadPool;
    private ExecutorService service;
    @PostConstruct
    private void init() {
        service = threadPool.getPool();
    }
    @Override
    public Result getCartGoodsCount() {
        Integer login = 0;
        try {
            login = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println(e);
            return Result.result(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, 0, System.currentTimeMillis());
        }
        Integer count = cartMapper.getCartGoodsCount(login);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, count, System.currentTimeMillis());
    }
    @Override
    public Result addCartGoods(DtsCartDto cartDto) {
        Integer login = 0;
        try {
            login = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println(e);
        }
        //{"
        //
        // ids":value}
        String specifications = cartDto.getSpecifications();
        specifications = specifications.substring(1, specifications.length() - 2); /**=> 颜色','规格','信息 */
        String[] split = specifications.split("','");
        List<String> strings = Arrays.asList(split);

        strings.forEach(s -> System.out.println("s = " + s));
        //判断购物车中是否含有同类规格的商品
        Integer res;
        Integer cartGoodsCount = 0;
        String commonGoods = goodsMapper.getCommonGoods(strings, cartDto.getGoodsId(), login);


        Map map = goodsMapper.getCartInsertGoodsInfo(cartDto.getGoodsId(), strings);
        Integer number = Integer.parseInt(map.get("number").toString());
        //库存不足
        if (number < cartDto.getNumber()) {
            return Result.result(InfoCode.GOODS_NUMBER_UNENOUGH, InfoCode.MESS_GOODS_NUMBER_UNENOUGH, number, System.currentTimeMillis());
        }

        if (commonGoods != null) {
            //有相同的商品规格(修改数量)
            res = cartMapper.updateGoodsNumber(cartDto.getNumber(), Integer.parseInt(commonGoods));
        } else {
            //没有相同的商品规格
            // 创建 JSON 数组
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode jsonArray = mapper.createArrayNode();
            for (String element : strings) {
                String trimmedElement = element.trim();
                // 只添加非空元素
                if (!trimmedElement.isEmpty()) {
                    jsonArray.add(new TextNode(trimmedElement));
                }
            }
            String jsonOutput = "";
            // 将 JSON 数组转为字符串
            try {
                jsonOutput = mapper.writeValueAsString(jsonArray);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            cartDto.setSpecifications(jsonOutput);
            map.put("userId", login);
            map.put("specifications", cartDto.getSpecifications());
            map.put("goodsId", cartDto.getGoodsId());
            map.put("goodsNumber", cartDto.getNumber());
            res = cartMapper.addCartGoods(map);
            cartGoodsCount = cartMapper.getCartGoodsCount(login);
        }

        Map maps = new HashMap();
        maps.put("res", res);
        maps.put("count", cartGoodsCount);
        if (res > 0) {
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, maps, System.currentTimeMillis());
        }
        return Result.fail(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, System.currentTimeMillis());
    }
    @Override
    public Result getCartInfoByUid() {
        Integer login = 0;
        try {
            login = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println(e);
        }
        List<Map> cartList = cartMapper.getCartInfoByUid(login);
        if (cartList == null || cartList.isEmpty()) {
            return null;
        }

        // 使用一个新的列表来存放处理后的结果
        List<Map<String, Object>> mergedCartList = new ArrayList<>();
        List<Integer> deletedNum = new ArrayList<>();
        for (int i = 0; i < cartList.size(); i++) {
            Map<String, Object> currentItem = cartList.get(i);
            Integer goodsId = (Integer) currentItem.get("productId");

            boolean isMerged = false;
            for (Map<String, Object> item : mergedCartList) {
                if (goodsId.equals(item.get("productId"))) {
                    // 合并数量
                    int newCartNumber = (Integer) item.get("cartNumber") + (Integer) currentItem.get("cartNumber");
                    item.put("cartNumber", newCartNumber);
                    isMerged = true;
                    deletedNum.add(i); // 记录删除的下标
                    break;
                }
            }
            if (!isMerged) {
                // 如果没有合并，添加到新列表
                mergedCartList.add(new HashMap<>(currentItem)); // 复制当前项
            }
        }
        // 删除已合并的项
        // 遍历时从最后一个索引开始删除，以避免删除时影响索引
        for (int i = deletedNum.size() - 1; i >= 0; i--) {
            int index = deletedNum.get(i);
            cartList.remove(index);
        }
        cartList.addAll(mergedCartList);
        Map<String, List<Map>> groupedByBrandId = mergedCartList.stream()
                .collect(Collectors.groupingBy(
                        item -> String.valueOf(item.get("brandId"))
                ));

        Map<Integer, List<Map>> result = groupedByBrandId.entrySet().stream()
                .collect(Collectors.toMap(
                        entry -> Integer.parseInt(entry.getKey()), // 将 String 转换为 Integer
                        Map.Entry::getValue // 获取对应的 List<Map>
                ));

        Integer cartGoodsCount = cartMapper.getCartGoodsCount(login);
        Map maps = cartMapper.getCartTotalInfoByUid(login);

        Map map = new HashMap();
        map.put("carTotal", maps);
        map.put("cartList", result);
        map.put("cartGoodsCount", cartGoodsCount);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
    }
    @Override
    public Result checkedGoods(Map map) {
        Integer login = 0;
        try {
            login = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println(e);
        }
        Integer productId = null;
        if (map.get("productId") != null) {
            productId = Integer.parseInt(map.get("productId").toString());
        }
        Boolean flag = Boolean.valueOf(map.get("isChecked").toString());
        cartMapper.changeChecked(productId, flag, login);
        return getCartInfoByUid();
    }
    @Override
    public Result changeNumber(Map map) {
        Integer res = cartMapper.updateNumber(map);
        if (res > 0) {
            return getCartInfoByUid();
        }
        return Result.fail(InfoCode.OK, InfoCode.MESSAGE_OK, System.currentTimeMillis());
    }
    @Override
    public Result minusCarGoods(List<Integer> ids) {
        Integer res = cartMapper.minusCarGoods(ids);
        if (res != null || res > 0) {
            //成功
            return getCartInfoByUid();
        }
        return Result.fail(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, System.currentTimeMillis());
    }
}
